﻿using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;
using System.Text.RegularExpressions;

namespace RuoVea.ExUtil.Validate;


/// <summary>
/// 数据验证器
/// </summary>
public class DataValidationAttribute : ValidationAttribute
{
    MetadataItemAttribute _metadataItem;

    /// <summary>
    /// 数据验证器
    /// </summary>
    /// <param name="validationType"></param>
    public DataValidationAttribute(ValidationTypes validationType)
    {
        _metadataItem = To(validationType);
        this.ErrorMessage = _metadataItem?.DefaultErrorMessage;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="data"></param>
    /// <returns></returns>
    private MetadataItemAttribute To(ValidationTypes data)
    {
        FieldInfo? fileInfo = data.GetType().GetField(data.ToString());
        var medata = fileInfo?.GetCustomAttributes(typeof(MetadataItemAttribute), false).FirstOrDefault();
        if (medata == null) return null;
        return (MetadataItemAttribute)medata;
    }
    /// <summary>
    /// 自定义规则
    /// </summary>
    /// <param name="validationType"></param>
    /// <param name="message"></param>
    public DataValidationAttribute(ValidationTypes validationType, string message)
    {
        _metadataItem = To(validationType);
        this.ErrorMessage = message;
    }

    /// <summary>
    /// 证请求结果
    /// </summary>
    /// <param name="value">校验内容</param>
    /// <param name="validationContext">报错指定对象</param>
    /// <returns>证请求结果的容器</returns>
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
        if (_metadataItem.RegularExpression.IsNullOrWhiteSpace()) return new ValidationResult("表达式不能为空");

        if (value != null)
        {
            Regex r = new Regex(_metadataItem.RegularExpression, _metadataItem.RegexOptions);
            if (!r.IsMatch(value + ""))
            {
                var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                return new ValidationResult(errorMessage);
            }
        }
        return ValidationResult.Success;
    }
}
